#!/user/bin/env python3
# -*- coding: utf-8 -*-

import time,os
import allure,json
from common.logger import Logger
class BasePage:
    def __init__(self,driver):
        self.driver=driver

    def exists_element(self,ele,value,doc,number=10,exists_type=2,screenshot=3):
        if exists_type == 1:  # 查找元素是否存后点击，不存在会报错
            for i in range(number):
                if ele.exists:
                    Logger.info("“{}”-元素“{}”已找到[{}]……".format(doc, value, i))
                    # time.sleep(timesleep)
                    if screenshot in [0,2]:
                        self.save_screenshot("{}-{}".format(doc, "元素操作之前截图"),screen_type=1)
                    return ele
                time.sleep(1)
                Logger.info('“{}”-元素“{}”，未找到，重新再找[{}]'.format(doc, value, i))
            # return self.driver(**type_dic)
            self.save_screenshot("{}-{}".format(doc, "找不到元素"))
            Logger.error(('“{}”-元素“{}”，找了好久都没找到……o(╯□╰)o……'.format(doc, value)))
            raise ValueError('“{}”-元素“{}”，找了好久都没找到……o(╯□╰)o……'.format(doc, value))

        elif exists_type == 2:  ##查找元素是否存，存在返回True，不存在返回False
            for i in range(number):
                if ele.exists:
                    Logger.info("“{}”-元素“{}”已找到[{}]……".format(doc, value, i))
                    return True
                time.sleep(1)
                Logger.info('“{}”-元素“{}”，未找到，重新再找[{}]'.format(doc, value, i))
            # return self.driver(**type_dic)
            Logger.info('“{}”-元素“{}”，未找到，不执行，跳过“{}”'.format(doc, value, doc))
            # self.save_screenshot("{}-{}".format(doc, "找不到元素"))

            return False


    def find_element(self, by_type,value, doc="", number=10,exists_type=1,screenshot=3):# 定位
        '''

        :param by_type:
        :param value:
        :param doc:
        :param number:
        :param exists_type:
        :param screenshot:  0：元素操作之前截图 1：元素操作之后截图 2：元素操作前后都截图 3：不截截图
        :return:
        '''


        # 判断元素是否存在，number查找次数，exists_type查找存在类型
        # self.d.locate('text', '立即开始', doc='立即开始', number=8, exists_type=2) == True:  # 判断元素是否存在，number查找次数

        Logger.info([by_type,value, doc])
        if type(by_type) in [list, tuple] and len(by_type) > 1:
            '''
            添加两种定位方式
            d(resourceId="com.gsx.tiku:id/bt_login",text='登录').click()
            bt_login = (( Ui2By.RESOURCEID,Ui2By.TEXT), ("com.gsx.tiku:id/bt_login","登录"))# 登录按钮
            '''

            dict_data = dict(zip(by_type, value))
            ele = self.driver(**dict_data)
            return self.exists_element(ele, value, doc, number, exists_type,screenshot=screenshot)

        else:
            if by_type.lower() == "text".lower():
                type_dic = {"text": value}
                ele = self.driver(**type_dic)
                return self.exists_element(ele, value, doc, number, exists_type,screenshot=screenshot)


            elif by_type.lower() == "resourceId".lower():  # “AKJLK”.lower()字母转为小写
                type_dic = {"resourceId": value}
                ele = self.driver(**type_dic)
                return self.exists_element(ele, value, doc, number, exists_type,screenshot=screenshot)

            elif by_type.lower() == "description".lower():
                type_dic = {"description": value}
                ele = self.driver(**type_dic)
                return self.exists_element(ele, value, doc, number, exists_type,screenshot=screenshot)

            elif by_type.lower() == "XPath".lower():
                ele = self.driver.xpath(value)
                return self.exists_element(ele, value, doc, number, exists_type,screenshot=screenshot)
            Logger.error("“by_type”的可选关键字为XPath, text,resourceId")



        # 截图操作
    def save_screenshot(self, doc, timesleep=0,screen_type=0):
        """  知识点解析      #time strftime() 函数接收以时间元组，并返回以可读字符串表示的当地时间，格式由参数 format 决定。"""
        # 图片名称  页面名称  操作名称   时间  png screencap
        file_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)) + "/png/{}_{}.png".format(doc,
                                                                                                         time.strftime(
                                                                                                             "%y%m%d-%H%M%S",time.localtime())))

        try:
            time.sleep(timesleep)
            self.driver.screenshot(file_path)
            Logger.info("截图成功，文件路径:{}".format(file_path))

            if screen_type == 0:
                with allure.step(doc):
                    allure.attach.file(file_path, doc, allure.attachment_type.PNG)
                    return file_path
            if screen_type == 1:
                allure.attach.file(file_path, doc, allure.attachment_type.PNG)
                return file_path
        except:
            Logger.exception("{}-截图失败！！！".format(doc))

    #
    # def click_element(self, by_type, value, doc=None, timesleep=2, TimeSleepBack=0.5, number=30):  # 点击元素,后检查元素是否完成跳转，界面发送变化后跳出继续执行
    #     self.click_element(by_type,value,doc,timesleep,TimeSleepBack,number)
    #     n=1
    #     while True:
    #         if n>=10:
    #             break
    #         elif self.find_element(by_type, value, doc, number, exists_type=2):
    #             self.click_element(by_type, value, doc, timesleep, TimeSleepBack, number)
    #             time.sleep(1)
    #         else:
    #             break
    #         n+=1






    def click_elements(self,by_type,value,doc=None,timesleep=2,TimeSleepBack=0.5,number=30,screenshot=3 ):#点击元素
        '''

        :param by_type: 元素定位类型
        :param value: 元素定位值
        :param doc:   元素操作描述
        :param timesleep: 坐标点击前等待时间
        :param TimeSleepBack: 点击后等待时间
        :param number: 元素操作次数
        :param screenshot: 默认为3，不截图  0：元素操作之前截图 1：元素操作之后截图 2：元素操作前后都截图 3：不截截图
        :return:
        '''
        with allure.step(doc):
            # allure.step(doc)
            if by_type.lower() == 'position'.lower():
                time.sleep(timesleep)
                self.driver.click(*value)
                time.sleep(TimeSleepBack)

                Logger.info('点击“%s”完成' % doc)
                # Logger.info('点击“%s”完成' % doc)
            else:
                try:
                    ele = self.find_element(by_type, value, doc, number=number,screenshot=screenshot)
                    Logger.info(ele)
                    time.sleep(timesleep)
                    ele.click_exists(timeout=10)
                    time.sleep(1.5)
                    if screenshot in [1,2]:
                        self.save_screenshot("{}-{}".format(doc, "元素点击之后截图"),screen_type=1)


                    Logger.info("“{}”-元素“{}”点击成功".format(doc, value))
                    # Logger.info('点击“%s”完成' % doc)
                except:
                    Logger.exception("“{}”-元素点击失败-“{}”".format(doc, value))
                    self.save_screenshot("{}-{}".format(doc, "点击失败"))
                    # self.save_screenshot("{}-点击失败".format(doc))
                    raise ValueError("{}-{}".format(doc, "点击失败"))

    def send_keys(self,by_type,value,text_value,doc=None,inputType='set_text',clear=False,enter=False,timesleep=0.5,number=30,screenshot=3):# 输入
        '''
                :param by_type: 定位方式
                :param value: 定位值
                :param text_value: 输入值
                :param doc: 操作内容
                :param inputType: 输入类型："shell" adb 方式输入,"set_text","send_keys"
                :param clear:输入之前输入清除数据  True False
                :param timesleep:输入前等待事件
                :param number:查找元素次数
                :param screenshot: 默认为3，不截图  0：元素操作之前截图 1：元素操作之后截图 2：元素操作前后都截图 3：不截截图
                :return:
                '''

        with allure.step("%s：输入【%s】"%(doc,text_value)):
            allure.attach(
                json.dumps(text_value, ensure_ascii=False, indent=4),
                "输入内容",
                allure.attachment_type.TEXT,
            )
            try:

                ele = self.find_element(by_type, value, doc, number=number,screenshot=screenshot)
                Logger.info(ele)
                time.sleep(timesleep)
                ele.click()

                if clear == True:  # 开启清除，默认为True输入前自动清除
                    self.driver.clear_text()  # 这里是清除指定元素的内容
                if inputType.lower() == 'shell'.lower():  # adb shell input text '输入'方式输入
                    self.driver.set_fastinput_ime(True)  # 切换输入法
                    os.system(f'adb -s {self.driver.device_info["serial"]} shell input text {str(text_value)}')
                    self.driver.set_fastinput_ime(False)  # 输入法用完记得关掉

                if inputType.lower() == 'set_text'.lower():  # set_text输入
                    self.driver.set_fastinput_ime(True)  # 切换输入法
                    ele.set_text(str(text_value))
                    self.driver.set_fastinput_ime(False)  # 输入法用完记得关掉

                if inputType.lower() == 'send_keys'.lower():  # send_keys输入
                    self.driver.set_fastinput_ime(True)  # 切换输入法
                    ele.send_keys(str(text_value))
                    self.driver.set_fastinput_ime(False)  # 输入法用完记得关掉

                if enter == True:  # 输入完成后点击回车，默认False为不点回车
                    self.driver.press("enter")

                Logger.info("“{}”-元素“{}”填写信息成功".format(doc, value))

                time.sleep(1.5)
                if screenshot in [1, 2]:
                    self.save_screenshot("{}-{}".format(doc, "元素输入之后截图"),screen_type=1)

            except:
                Logger.exception("“{}”-元素，填写信息失败-“{}”".format(doc, value))
                self.save_screenshot("{}-{}".format(doc, "填写信息失败"))
                raise ValueError("{}-{}".format(doc, "填写信息失败"))

    def toast_message(self):
        message = self.driver.toast.get_message()  # 获取提示内容
        Logger.info("获取toast消息为：%s" % message)
        return message



    # 断言元素文本包含指定值
    def assert_text(self, by_type,value,expect_text,doc=None,info_type='text',assert_type="element",number=10,screenshot=3):
        '''
        :param by_type:
        :param value:
        :param expect_text:
        :param doc:
        :param info_type:
        :return:

        info_type :className,resourceName,text,contentDescription

                         {
            'bounds': {
                'bottom': 1080,
                'left': 1780,
                'right': 1920,
                'top': 0
            },
            'childCount': 1,
            'className': 'android.widget.RelativeLayout',
            'contentDescription': None,
            'packageName': 'com.qdmetro.xahl.ar.project',
            'resourceName': 'com.qdmetro.xahl.ar.project:id/ll_Right',
            'text': None,
            'visibleBounds': {
                'bottom': 1080,
                'left': 1780,
                'right': 1920,
                'top': 0
            },
            'checkable': False,
            'checked': False,
            'clickable': False,
            'enabled': True,
            'focusable': False,
            'focused': False,
            'longClickable': False,
            'scrollable': False,
            'selected': False
        }


        '''
        text=''
        try:
            if assert_type=="element":#元素获取元素属性断言
                element_info = self.find_element(by_type,value, doc=doc, number=number,screenshot=screenshot).info
                Logger.info(element_info)
                text = element_info[info_type]
                #text = self.get_text(by_type,value,doc)[info_type]
            elif assert_type=="toast":#获取toast消息断言
                text=self.toast_message()

            self.save_screenshot("{}-{}".format(doc, 'True'))
            result = expect_text in str(text)
            Logger.info('{}-元素{}文本预期为"{}"，实际为"{}"，用例执行结果为- [{}]'.format(doc, value, expect_text, text, result))

        except:
            Logger.exception("{}-获取文本失败，用例执行失败！！！".format(doc))
            self.save_screenshot("{}-{}".format(doc, 'False'))
            return False
